import { DeleteOutlined, DownloadOutlined, EyeOutlined, UploadOutlined } from '@ant-design/icons';
import { Upload, Button, Space, message, UploadFile, UploadProps } from 'antd';
import React, { useState, useRef, useEffect } from 'react';

import type { RcFile } from 'antd/es/upload';
import {UploadFileStatus} from "antd/es/upload/interface";

interface VideoUploaderProps {
  maxCount?: number; // 最大上传数量
  maxSize?: number; // 单个视频最大大小（MB）
  accept?: string; // 接受的文件类型
  onUploadSuccess: (fileUrls: string[]) => void; // 上传成功回调
  videoList: string[];
}

export default function VideoUploader({
  maxCount = 1,
  maxSize = 20,
  accept = 'video/*',
  onUploadSuccess,
  videoList,
}: VideoUploaderProps) {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [previewVideo, setPreviewVideo] = useState<string>('');
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewTitle, setPreviewTitle] = useState('');
  const uploadRef = useRef<any>(null);

  // 上传前的校验
  const beforeUpload = (file: RcFile) => {
    const isVideo = file.type.includes('video/');
    if (!isVideo) {
      message.error('只能上传视频文件!');
      return Upload.LIST_IGNORE;
    }

    const isLtMaxSize = file.size / 1024 / 1024 < maxSize;
    if (!isLtMaxSize) {
      message.error(`视频大小不能超过 ${maxSize}MB!`);
      return Upload.LIST_IGNORE;
    }

    return true;
  };
  useEffect(() => {
    console.log(videoList);

    if (videoList.length > 0) {
      setFileList(
        videoList.map((item, index) => ({
          uid: item,
          name: item?.replace('https://zdhy-1342415571.cos.ap-chengdu.myqcloud.com/T68/', ''),
          status: 'done',
          url: item,
          response: {
            success: item,
          },
        })),
      );
    }
  }, [videoList]);
  // 处理上传变化
  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    setFileList(newFileList);
    onUploadSuccess(newFileList.map((item) => item.response?.success));
    setPreviewVideo(newFileList[0]?.url || '');
  };

  // 预览视频
  const handlePreview = async (file: UploadFile) => {
    console.log(file);

    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as RcFile);
    }
    setPreviewVideo(file.url || (file.preview as string));
    setPreviewOpen(true);
    setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
  };
  useEffect(() => {
    console.log(fileList);
  }, [fileList]);
  // 下载视频
  const handleDownload = (file: UploadFile) => {
    console.log(file);

    const link = document.createElement('a');
    link.href = file.response.success || (file.preview as string);
    link.download = file.name || 'video';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // 删除视频
  const handleRemove = (file: UploadFile) => {
    const newFileList = fileList.filter((item) => item.uid !== file.uid);
    setFileList(newFileList);
  };

  // 重新上传
  const handleReupload = (file: UploadFile) => {
    handleRemove(file);
    uploadRef.current?.uploader.uploadBatch();
  };

  // 自定义操作项
  const renderActionButtons = (file: UploadFile) => (
    <Space size="small">
      <Button
        type="text"
        icon={<EyeOutlined />}
        onClick={(e) => {
          e.stopPropagation();
          handlePreview(file);
        }}
        title="预览"
      />
      <Button
        type="text"
        icon={<DownloadOutlined />}
        onClick={(e) => {
          e.stopPropagation();
          handleDownload(file);
        }}
        title="下载"
      />
      <Button
        type="text"
        icon={<DeleteOutlined />}
        onClick={(e) => {
          e.stopPropagation();
          handleRemove(file);
        }}
        title="删除"
      />
      <Button
        type="text"
        onClick={(e) => {
          e.stopPropagation();
          handleReupload(file);
        }}
        title="重新上传"
      >
        重新上传
      </Button>
    </Space>
  );

  // 自定义上传列表项
  const renderUploadListItem = (originNode: React.ReactNode, file: UploadFile) => (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
      <div style={{ flex: 1, cursor: 'default' }} onClick={null}>
        {originNode}
      </div>
      {/* <div>{renderActionButtons(file)}</div> */}
    </div>
  );

  return (
    <>
      <Upload
        data={{ group: 'T68' }}
        showUploadList={{
          showRemoveIcon: true, // 控制是否显示删除图标，默认为true
          showDownloadIcon: true, // 控制是否显示下载图标，默认为false
          showPreviewIcon: true, // 控制是否显示预览图标，默认为false
        }}
        onDownload={handleDownload}
        ref={uploadRef}
        action="/api/file/oss/upload" // 替换为你的上传接口
        listType="text"
        fileList={fileList}
        onChange={handleChange}
        beforeUpload={beforeUpload}
        onPreview={handlePreview}
        accept={accept}
        maxCount={maxCount}
        itemRender={(originNode, file) => renderUploadListItem(originNode, file)}
      >
        {fileList.length >= maxCount ? null : <Button icon={<UploadOutlined />}>上传视频</Button>}
      </Upload>

      {/* <Modal
        open={previewOpen}
        title={previewTitle}
        footer={null}
        onCancel={() => setPreviewOpen(false)}
        style={{ top: 20 }}
      >
        <video controls autoPlay style={{ width: '100%' }}>
          <source src={previewVideo} type="video/mp4" />
          您的浏览器不支持视频播放
        </video>
      </Modal> */}
    </>
  );
}

// 辅助函数：将文件转换为base64
function getBase64(file: RcFile): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });
}
